import { asyncRouterMap, constantRouterMap } from '@/router'

function hasPermission(item) {
  let r = null
  for(let i=0;i < asyncRouterMap.length;i++) {
    if(asyncRouterMap[i].redirect === item.functionUri) {
      r = asyncRouterMap[i]
      r.children[0].meta.title = item.functionName
      break
    }
  }
  return r
}

function filterAsyncRouter(roles) {
  let m = [
    {
      path: '*',
      redirect: '/empty'
    }
  ]
  roles.map(item => {
    if (item.children.length > 0) {
      item.children.map(item2 => {
        if(hasPermission(item2)) {
          m.push(hasPermission(item2))
        } else {
          console.log(item2.functionUri)
        }
      })
    } else {
      if(hasPermission(item)) {
        m.push(hasPermission(item))
      }
    }
  })
  return m;
}

const permission = {
  state: {
    menu:[],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, roles) => {
      state.menu = roles
      state.addRouters = filterAsyncRouter(roles)
    }
  },
  actions: {
    GenerateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        commit('SET_ROUTERS', roles)
        resolve()
      })
    }
  }
}

export default permission
